import {
  getInspectionTaskByPage,
  exportInspectionTask,
  getInspectionTaskById,
} from '@/services/quality/inspectionTask';
import { viewBaseInfo } from '@/services/quality/productQuality';
import InspectionFileInfo from './inspectionFileInfo';
import {
  stagingInspectionTask,
  submitInspectionTask,
} from '@/services/product/productManufactInforExecute';
import { PlusOutlined } from '@ant-design/icons';
import type { DataType, tabType, record_quality_Type } from './components/interfacequality';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useRef, useState } from 'react';
import { Button, message, Tabs, Input, Space, Descriptions, Modal, Radio, Checkbox } from 'antd';
import './styles.less';
import '../product/templatestyle.less';
import { Ellipsis } from '@/components/Ellipsis';
import { tableSearchPublicConfig } from '@/utils/filterUtils';

const InspectionTask: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [lookOrUpdate, setLookOrUpdate] = useState(false); //编辑框的disable
  const [lookVisit, setLookVisit] = useState(false);
  const [lookInfo, setLookInfo] = useState<lookInfoType>();
  const ref = useRef(null);
  const [thehead, setthehead] = useState([]); //预览用，保存表头
  const [theitem, settheitem] = useState([]); //预览用，保存项
  const [thetitle, setthetitle] = useState('');
  const [thetitleInfo, setTitileInfo] = useState<any>();
  const [pageState, setPageState] = useState('');
  const values: any[] = [];
  const taskState = ['未完成', '已完成'];
  const [currentmemberid, setcurrentmemberid] = useState('');
  const [quality_Record, setquality_Record] = useState<record_quality_Type>();
  const [open, setOpen] = useState(false); //控制查看Modal的开关
  const { TextArea } = Input;
  const [submit_open, setsubmit_open] = useState(false); //确认检验的弹窗开关
  const [tabState, setTabState] = useState('1'); //用于判断tab在“未完成”还是“已完成”状态

  // 自检清单提交
  const handleSubmit_template = async () => {
    console.log(theitem);
    let isFormFilled = 1;
    for (let index in theitem) {
      if (theitem[index].rightValue == null && theitem[index].descValue == null) {
        isFormFilled = 0;
        break;
      }
    }
    if (isFormFilled == 1) {
      const result = await submitInspectionTask({
        inspectionCostomValueDtoList: thehead,
        inspectionItemDtoList: theitem,
        inspectionTask: thetitleInfo,
      });
      if (result && result.code === 0) {
        message.success(result.message);
      }
      actionRef.current!.reload();
    } else {
      message.warning('评审单仍有未填写项');
    }
  };

  //自检清单暂存
  const handleSave_template = async () => {
    console.log(theitem);
    let isFormFilled = 1;
    for (let index in theitem) {
      if (theitem[index].rightValue == null && theitem[index].descValue == null) {
        isFormFilled = 0;
        break;
      }
    }
    if (isFormFilled == 1) {
      const result = await stagingInspectionTask({
        inspectionCostomValueDtoList: thehead,
        inspectionItemDtoList: theitem,
        inspectionTask: thetitleInfo,
      });
      if (result && result.code === 0) {
        message.success('保存成功');
      }
      actionRef.current!.reload();
    } else {
      message.warning('评审单仍有未填写项');
    }
  };

  //取消编辑Modal的弹窗
  const edit_handleCancel = () => {
    setOpen(false);
    setthehead([]);
    settheitem([]);
    setthetitle('');
  };

  const tabList_modal: tabType[] = [
    {
      name: 'tab1',
      label: '详细信息',
      content: (
        <div style={{ height: 500, width: 800 }}>
          <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
            <Descriptions title="" bordered column={2}>
              <Descriptions.Item label="工单编号">
                {quality_Record?.wo ? quality_Record?.wo : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="项目编号">
                {quality_Record?.projectCode ? quality_Record?.projectCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="批次编号">
                {quality_Record?.batchProductCode ? quality_Record?.batchProductCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="当前批次">
                {quality_Record?.currentBatch ? quality_Record?.currentBatch : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="柜体类型">
                {quality_Record?.productType ? quality_Record?.productType : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="柜体编号">
                {quality_Record?.productCode ? quality_Record?.productCode : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="检验状态">
                {quality_Record?.status == 0 ? '未检验' : '已检验'}
              </Descriptions.Item>
            </Descriptions>
          </Space>
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '检验表',
      content: (
        <div style={{ height: 500 }}>
          {/* 模板预览 */}
          <div className="templatebox">
            <div className="pdName">{thetitle == '' ? '暂时没有工序检验表' : thetitle}</div>
            <div className="company">
              <div className="company_name">电柜管家</div>
              <div className="triangle"></div>
              <ul className="title_list">
                {thehead?.map((item, index) => {
                  return <li key={index}>{item?.name + ':' + item?.templateCustomItemValue}</li>;
                })}
              </ul>
            </div>
            <ul className="list">
              {theitem?.map((item, index) => {
                if (item?.optionType == '单选') {
                  let selectOption = item?.rightOption.split('|');
                  if (item?.isDetailDes == '1') {
                    //有描述框
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Input
                              className="detailinput"
                              defaultValue={item.descValue}
                              value={values[item.sortId]}
                              disabled={tabState === '2'}
                              onChange={(e) => {
                                values[item.sortId] = e.target.value;
                                item.descValue = e.target.value;
                              }}
                              placeholder={'请输入描述内容'}
                            />
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            options={selectOption}
                            disabled={tabState === '2'}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            options={selectOption}
                            disabled={tabState === '2'}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '多选') {
                  const thedescOption = item?.descOption.split('|');
                  if (item?.isExtendDes == '1') {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              options={thedescOption}
                              disabled={tabState === '2'}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                            <div className="other">
                              <div>
                                <span>*</span>如果没有合适选项，请文字描述:
                              </div>
                              <Input
                                className="detailinput"
                                disabled={tabState === '2'}
                                defaultValue={item.multiDesValue}
                                value={values[item.sortId]}
                                onChange={(e) => {
                                  values[item.sortId] = e.target.value;
                                  item.multiDesValue = e.target.value;
                                }}
                                placeholder={'请输入描述内容'}
                              />
                            </div>
                          </div>
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              options={thedescOption}
                              disabled={tabState === '2'}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                          </div>
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '描述') {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <TextArea
                            rows={3}
                            className="detailinput"
                            disabled={tabState === '2'}
                            placeholder={'请输入描述内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                } else {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Input
                            className="detailinput"
                            disabled={tabState === '2'}
                            placeholder={'请输入填空内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                }
              })}
            </ul>
            <ul className="list">
              <li className="list_item">
                <div className="question_wrapper">
                  <div className="title">备注</div>
                  <div className="templatecontent">
                    <Input
                      className="detailinput"
                      disabled={tabState === '2'}
                      placeholder={'请输入填空内容'}
                      defaultValue={thetitleInfo?.memo}
                      // value={values[item.sortId]}
                      onChange={(e) => {
                        // values[item.sortId] = e.target.value;
                        thetitleInfo.memo = e.target.value;
                      }}
                    />
                  </div>
                </div>
              </li>
            </ul>
            <hr />
            <div style={{ width: 900, textAlign: 'center' }}>
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                disabled={quality_Record?.status == 1 || tabState === '2'}
                onClick={() => {
                  handleSave_template();
                }}
              >
                保存
              </Button>
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                disabled={quality_Record?.status == 1 || tabState === '2'}
                onClick={async () => {
                  const isNullArray = theitem.map((item: any, index: any) => {
                    const temp = [
                      (item.optionType == '单选' || item.optionType == '多选') &&
                        item.rightValue == null,
                      item.optionType == '填空' && item.descValue == null,
                      item.descValue == '',
                    ];
                    const trueCount = temp.filter((item) => item == true);
                    if (trueCount.length >= 1) {
                      return true;
                    } else {
                      return false;
                    }
                  });
                  if (isNullArray.includes(true)) {
                    message.warning('检验单有未填项');
                  } else {
                    // 获取当前用户、时间
                    const getuserlist = await viewBaseInfo(null);
                    if (getuserlist && getuserlist?.code == 0) {
                      message.success('提交成功');
                    }
                    setcurrentmemberid(getuserlist.data.id);
                    const result_template = await submitInspectionTask({
                      inspectionCostomValueDtoList: thehead,
                      inspectionItemDtoList: theitem,
                      inspectionTask: thetitleInfo,
                    });
                    if (result_template && result_template.code == 0) {
                      message.success('提交成功');
                    }
                    setsubmit_open(true);
                  }
                }}
              >
                提交
              </Button>
            </div>
          </div>
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '检验附件',
      content: (
        <div style={{ height: 500 }}>
          <InspectionFileInfo
            theid={quality_Record?.id}
            thestatus={quality_Record?.status}
            type={quality_Record?.type}
          />
        </div>
      ),
    },
  ];

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目名称',
      align: 'center',
      sorter: true,

      width: 200,
      dataIndex: 'projectName',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目编号',

      width: 200,
      align: 'center',
      sorter: true,
      dataIndex: 'projectCode',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '当前批次',
      width: 150,
      align: 'center',
      sorter: true,
      dataIndex: 'currentBatch',
      render: (text, record) => (
        <div>
          {text}/{record.batchCount}
        </div>
      ),
    },
    {
      title: '工单编号',
      align: 'center',
      sorter: true,

      width: 180,
      dataIndex: 'wo',
      hideInTable: pageState === '2' || pageState === '1',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体编号',

      width: 180,
      dataIndex: 'batchProductCode',
      hideInTable: pageState === '2' || pageState === '1',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '模板名称',

      width: 200,
      align: 'center',
      sorter: true,
      dataIndex: 'templateName',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '完成人员',

      width: 120,
      align: 'center',
      sorter: true,
      dataIndex: 'finisher',
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '任务状态',
      dataIndex: 'state',
      width: 100,

      align: 'center',
      sorter: true,
      render: (text) => {
        return <div>{taskState[Number(text)]}</div>;
      },
    },
    {
      title: '创建日期', //表头显示的名称
      align: 'center',
      sorter: true,
      width: 100,
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      width: 100,
      align: 'center',
      sorter: true,
      dataIndex: 'createName',
    },
    // {
    //   title: '操作',
    //   width: 220,
    //  align: 'center',sorter: true,
    //   valueType: 'option',
    //   key: 'option',
    //   fixed: 'right',
    //   render: (text, record, _, action) => [
    //     <a
    //       key="lookKey"
    //       onClick={async () => {
    //         const template = await getInspectionTaskById(record.id);
    //         console.log(template, 'template');
    //         if (template != undefined) {
    //           setTitileInfo(template.data.inspectionTask);
    //           setthetitle(template.data.inspectionTask?.templateName);
    //           setthehead(template.data.inspectionCostomValueExList);
    //           settheitem(template.data.inspectionItemExList);
    //         }
    //         setModalVisit(true);
    //         setFormTitle(`查看工单-${record.processName}`);
    //         setLookVisit(true);
    //         setLookOrUpdate(true);
    //         actionRef.current!.reload();
    //       }}
    //     >
    //       查看
    //     </a>,
    //     <a key="printKey" onClick={() => {}}>
    //       打印
    //     </a>,
    //     !record.state && (
    //       <a
    //         key="keepKey"
    //         onClick={async () => {
    //           setLookOrUpdate(false);
    //           const template = await getInspectionTaskById(record.id);
    //           if (template != undefined) {
    //             setTitileInfo(template.data.inspectionTask);
    //             setthetitle(template.data.inspectionTask?.templateName);
    //             setthehead(template.data.inspectionCostomValueExList);
    //             settheitem(template.data.inspectionItemExList);
    //           }
    //           setModalVisit(true);
    //           setFormTitle(`查看工单-${record.processName}`);
    //           setLookVisit(true);
    //           actionRef.current!.reload();
    //         }}
    //       >
    //         维护
    //       </a>
    //     ),
    //     // !record.state && (
    //     //   <a
    //     //     key="deleteKey"
    //     //     onClick={() => {
    //     //       Modal.confirm({
    //     //         title: '删除',
    //     //         content: '确定要删除吗',
    //     //         okText: '确认',
    //     //         cancelText: '取消',
    //     //         onOk: async () => {
    //     //           await delInspectionTask({ id: record.id });
    //     //           actionRef.current!.reload();
    //     //         },
    //     //       });
    //     //     }}
    //     //   >
    //     //     删除
    //     //   </a>
    //     // ),
    //     !record.state && (
    //       <a
    //         key="finishKey"
    //         onClick={async () => {
    //           const result = await finishInspectionTask(record.id);
    //           if (result && result.code === 0) {
    //             message.success('更新成功');
    //             actionRef.current!.reload();
    //           }
    //         }}
    //       >
    //         完成
    //       </a>
    //     ),
    //   ],
    // },
    {
      title: '操作',
      width: 150,
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="lookKey"
          onClick={async () => {
            const template = await getInspectionTaskById(record.id);
            if (template != undefined) {
              setTitileInfo(template.data.inspectionTask);
              setthetitle(template.data.inspectionTask?.templateName);
              setthehead(template.data.inspectionCostomValueExList);
              settheitem(template.data.inspectionItemExList);
            }
            setquality_Record(record);
            setOpen(true);
            console.log(record, 'record');
            // setModalVisit(true);
            // setFormTitle(`查看工单-${record.processName}`);
            // setLookVisit(true);
            // setLookOrUpdate(true);
            actionRef.current!.reload();
          }}
        >
          检验
        </a>,
      ],
    },
  ];

  type inspectionTaskType = {
    id: string;
    createTime: string;
    createId: string;
    createName: string;
    updateTime: string;
    updateId: string;
    delete: number;
    inspectionTemplateId: string;
    type: string;
    templateName: string;
    processId: null | string;
    projectCode: string;
    infoId: string;
    projectName: string;
    wo: string;
    currentBatch: number;
    batchCount: number;
    state: number;
    finisher: null | string;
    inspector: null | string;
    memo: null | string;
    finishedTime: null | string;
    inspectTime: null | string;
  };

  type lookInfoType = {
    inspectionTask: inspectionTaskType;
    inspectionCostomValueExList: any;
    inspectionItemExList: any;
  };

  type tabsType = {
    key: string;
    name: string;
    label: string;
    content: JSX.Element;
  };

  const items1: tabsType[] = [
    {
      key: '0',
      name: 'tab1',
      label: `终检`,
      content: (
        <div>
          <ProTable
            headerTitle="检验填报查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTran(ref.current.getFieldsValue());
                  exportInspectionTask({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `InspectionTask.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters1 = filterTran(params);
              const filters = [
                {
                  andOr: 'and',
                  field: 'state',
                  operator: 'eq',
                  value: '0',
                },
                {
                  andOr: 'and',
                  field: 'type',
                  operator: 'eq',
                  value: '终检', //过程检验
                },
                ...filters1,
              ];
              const result = await getInspectionTaskByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      key: '1',
      name: 'tab2',
      label: `交检评审`,
      content: (
        <div>
          <ProTable
            headerTitle="检查执行表查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTran(ref.current.getFieldsValue());
                  exportInspectionTask({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `InspectionTask.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters1 = filterTran(params);
              const filters = [
                {
                  andOr: 'and',
                  field: 'state',
                  operator: 'eq',
                  value: '0',
                }, //未完成
                {
                  andOr: 'and',
                  field: 'type',
                  operator: 'eq',
                  value: '交检评审', //交检评审
                },
                ...filters1,
              ];
              const result = await getInspectionTaskByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      key: '2',
      name: 'tab3',
      label: `过程检验`,
      content: (
        <ProTable
          headerTitle="检查执行表查询"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          formRef={ref}
          search={{
            ...tableSearchPublicConfig,
          }}
          toolBarRender={(action, { selectedRows }) => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                const filters = filterTran(ref.current.getFieldsValue());
                exportInspectionTask({
                  current: 1,
                  pageSize: 5000,
                  filters: filters,
                }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `InspectionTask.xls`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              导出
            </Button>,
          ]}
          request={async (params = {}, sort, filter) => {
            const sorters = sortTran(sort);
            const filters1 = filterTran(params);
            console.log(filters1, 'filter1');
            const filters = [
              {
                andOr: 'and',
                field: 'state',
                operator: 'eq',
                value: '0',
              },
              {
                andOr: 'and',
                field: 'type',
                operator: 'eq',
                value: '过程检验', //过程检验
              },
              ...filters1,
            ];
            const result = await getInspectionTaskByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            });
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          scroll={{ x: 1000, y: 350 }}
          rowSelection={{}}
        />
      ),
    },
  ];

  const items2: tabsType[] = [
    {
      key: '0',
      name: 'tab1',
      label: `终检`,
      content: (
        <div>
          <ProTable
            headerTitle="检查执行表查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTran(ref.current.getFieldsValue());
                  exportInspectionTask({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `InspectionTask.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters1 = filterTran(params);
              const filters = [
                {
                  andOr: 'and',
                  field: 'state',
                  operator: 'eq',
                  value: '1',
                },
                {
                  andOr: 'and',
                  field: 'type',
                  operator: 'eq',
                  value: '终检', //过程检验
                },
                ...filters1,
              ];
              const result = await getInspectionTaskByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      key: '1',
      name: 'tab2',
      label: `交检评审`,
      content: (
        <div>
          <ProTable
            headerTitle="检查执行表查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={{
              ...tableSearchPublicConfig,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTran(ref.current.getFieldsValue());
                  exportInspectionTask({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `InspectionTask.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters1 = filterTran(params);
              const filters = [
                {
                  andOr: 'and',
                  field: 'state',
                  operator: 'eq',
                  value: '1',
                },
                {
                  andOr: 'and',
                  field: 'type',
                  operator: 'eq',
                  value: '交检评审', //交检评审
                },
                ...filters1,
              ];
              const result = await getInspectionTaskByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      key: '2',
      name: 'tab3',
      label: `过程检验`,
      content: (
        <ProTable
          headerTitle="检查执行表查询"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          formRef={ref}
          search={{
            ...tableSearchPublicConfig,
          }}
          toolBarRender={(action, { selectedRows }) => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                const filters = filterTran(ref.current.getFieldsValue());
                exportInspectionTask({
                  current: 1,
                  pageSize: 5000,
                  filters: filters,
                }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `InspectionTask.xls`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              导出
            </Button>,
          ]}
          request={async (params = {}, sort, filter) => {
            const sorters = sortTran(sort);
            const filters1 = filterTran(params);
            const filters = [
              {
                andOr: 'and',
                field: 'state',
                operator: 'eq',
                value: '1',
              },
              {
                andOr: 'and',
                field: 'type',
                operator: 'eq',
                value: '过程检验', //过程检验
              },
              ...filters1,
            ];
            const result = await getInspectionTaskByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            });
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          scroll={{ x: 1000, y: 350 }}
          rowSelection={{}}
        />
      ),
    },
  ];

  const items: tabsType[] = [
    {
      key: '0',
      name: 'tab1',
      label: `未完成`,
      content: (
        <div>
          <Tabs
            onChange={(e) => {
              setPageState(String(Number(e) - 1));
            }}
            style={{ backgroundColor: 'white', padding: '10px', paddingLeft: '20px' }}
            // type="card"
            defaultActiveKey="0"
            items={items1.map((item, i) => {
              const id = String(i + 1);
              return {
                label: item.label,
                key: id,
                children: <div>{item.content}</div>,
              };
            })}
          />
        </div>
      ),
    },
    {
      key: '1',
      name: 'tab2',
      label: `已完成`,
      content: (
        <div>
          <Tabs
            onChange={(e) => {
              setPageState(String(Number(e) - 1));
            }}
            style={{ backgroundColor: 'white', padding: '10px', paddingLeft: '20px' }}
            // type="card"
            defaultActiveKey="0"
            items={items2.map((item, i) => {
              const id = String(i + 1);
              return {
                label: item.label,
                key: id,
                children: <div>{item.content}</div>,
              };
            })}
          />
        </div>
      ),
    },
  ];

  const keepSubmit = async () => {
    const temp = [];
    lookInfo?.inspectionItemExList.map((item) => {
      temp.push({ id: item.id, value: item.value });
    });
    const result = await submitInspectionTask({
      inspectionTask: lookInfo?.inspectionTask,
      inspectionItemDtoList: temp,
    });
    lookInfo?.inspectionItemExList.map((item) => {
      item.value = '';
    });
    if (result && result.code === 0) {
      message.success('更新成功');
    }
    setLookVisit(false);
  };
  const onBlur = (e: any, index: any) => {
    const temp = lookInfo;
    temp.inspectionItemExList[index].value = e.target.value;
    setLookInfo(temp);
  };

  return (
    <>
      <Tabs
        destroyInactiveTabPane
        type="card"
        style={{ margin: '20px', padding: '10px' }}
        defaultActiveKey="0"
        onChange={(value) => {
          setTabState(value);
        }}
        items={items.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        className="lookModal"
        title="检查表执行查看"
        open={lookVisit}
        onOk={keepSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => {
          setLookVisit(false);
        }}
        footer={
          !lookOrUpdate ? (
            <div>
              <Button
                type="primary"
                hidden={thetitle == ''}
                onClick={() => {
                  handleSave_template();
                }}
              >
                保存
              </Button>
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                onClick={() => {
                  handleSubmit_template();
                }}
              >
                提交
              </Button>
            </div>
          ) : (
            ''
          )
        }
        width={1200}
        destroyOnClose
      >
        {/* 模板预览 */}
        <div className="templatebox" style={{ height: '600px', margin: 'auto' }}>
          <div className="pdName">{thetitle == '' ? '暂时没有工序检验表' : thetitle}</div>
          <div className="company">
            <div className="company_name">电柜管家</div>
            <div className="triangle"></div>
            <ul className="title_list">
              {thehead?.map((item, index) => {
                if (index + 1 == thehead.length) {
                  return <li key={index}>{item?.name + ':' + item?.templateCustomItemValue}</li>;
                } else {
                  return <li key={index}>{item?.name + ': ' + item?.templateCustomItemValue}</li>;
                }
              })}
            </ul>
          </div>
          <ul className="list">
            {theitem?.map((item, index) => {
              if (item?.optionType == '单选') {
                let selectOption = item?.rightOption.split('|');
                if (item?.isDetailDes == '1') {
                  //有描述框
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Input
                            disabled={lookOrUpdate}
                            className="detailinput"
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                            placeholder={'请输入描述内容'}
                          />
                        </div>
                      </div>
                      <div className="radio_wrapper">
                        <Radio.Group
                          disabled={lookOrUpdate}
                          options={selectOption}
                          defaultValue={item.rightValue}
                          onChange={(e) => {
                            item.rightValue = e.target.value;
                          }}
                        />
                      </div>
                    </li>
                  );
                } else {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                      </div>
                      <div className="radio_wrapper">
                        <Radio.Group
                          disabled={lookOrUpdate}
                          options={selectOption}
                          onChange={(e) => {
                            item.rightValue = e.target.value;
                          }}
                        />
                      </div>
                    </li>
                  );
                }
              } else if (item?.optionType == '多选') {
                let thedescOption = item?.descOption.split('|');
                if (item?.isExtendDes == '1') {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Checkbox.Group options={thedescOption} />
                          <div className="other">
                            <div>
                              <span>*</span>如果没有合适选项，请文字描述:
                            </div>
                            <Input
                              disabled={lookOrUpdate}
                              className="detailinput"
                              placeholder={'请输入描述内容'}
                              onChange={(e) => {
                                values[item.sortId] = e.target.value;
                                item.descValue = e.target.value;
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    </li>
                  );
                } else {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Checkbox.Group disabled={lookOrUpdate} options={thedescOption} />
                        </div>
                      </div>
                    </li>
                  );
                }
              } else if (item?.optionType == '描述') {
                return (
                  <li key={index} className="list_item">
                    <div className="question_wrapper">
                      <div className="title">
                        {index + 1}|{item?.itemName}
                        {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                          ? ':（' + item?.inspectionMethod + '）'
                          : ''}
                      </div>
                      <div className="templatecontent">
                        <TextArea
                          disabled={lookOrUpdate}
                          rows={3}
                          className="detailinput"
                          placeholder={'请输入描述内容'}
                        />
                        {/* <Input placeholder={'请输入描述内容'}/> */}
                      </div>
                    </div>
                  </li>
                );
              } else {
                return (
                  <li key={index} className="list_item">
                    <div className="question_wrapper">
                      <div className="title">
                        {index + 1}|{item?.itemName}
                        {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                          ? ':（' + item?.inspectionMethod + '）'
                          : ''}
                      </div>
                      <div className="templatecontent">
                        <Input
                          disabled={lookOrUpdate}
                          className="detailinput"
                          placeholder={'请输入填空内容'}
                          onChange={(e) => {
                            values[item.sortId] = e.target.value;
                            item.descValue = e.target.value;
                          }}
                        />
                      </div>
                    </div>
                  </li>
                );
              }
            })}
          </ul>
          <hr />
          {/* <div
            style={{ width: 770, textAlign: 'center', display: `${lookOrUpdate ? 'none' : ''}` }}
          >
            <Button
              type="primary"
              hidden={thetitle == ''}
              onClick={() => {
                handleSave_template();
              }}
            >
              保存
            </Button>
            <Button
              style={{ marginLeft: '20px' }}
              type="primary"
              hidden={thetitle == ''}
              onClick={() => {
                handleSubmit_template();
              }}
            >
              提交
            </Button>
          </div> */}
        </div>
      </Modal>
      <Modal
        open={open}
        title="检验"
        width={1200}
        style={{ marginTop: '-40px' }}
        onCancel={edit_handleCancel}
        destroyOnClose
        footer={[
          <Button key="back" onClick={() => edit_handleCancel()}>
            关闭
          </Button>,
        ]}
      >
        <Tabs
          tabPosition="top"
          items={tabList_modal.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        />
      </Modal>
    </>
  );
};
export default InspectionTask;
